package xyz.ibenben.zhongdian.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.common.exception.ExceptionEnum;
import xyz.ibenben.zhongdian.common.exception.MyException;
import xyz.ibenben.zhongdian.common.util.HttpServletResponseUtil;
import xyz.ibenben.zhongdian.system.entity.HouseImage;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.HouseImageForm;
import xyz.ibenben.zhongdian.system.service.HouseImageService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 房屋图像控制类
 * 提供了一些基本的服务，如初始化、获取房屋图像列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "houseImage";
    /**
     * 上传页面
     */
    private static final String UPLOADPAGE = ENTITYNAME + "/upload";

    @Resource
    private HouseImageService houseImageService;

    private final List<MultipartFile> files = new ArrayList<>();

    /**
     * 获取房屋图像信息列表
     *
     * @param map            参数
     * @param houseImageForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取房屋图像信息列表")
    public String getAll(Model map, @ModelAttribute HouseImageForm houseImageForm, HttpSession session) {
        HouseImageForm newHouseImageForm = new HouseImageForm();
        if (houseImageForm != null) {
            newHouseImageForm = houseImageForm;
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newHouseImageForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newHouseImageForm);
        Page<HouseImage> page = new Page<>(newHouseImageForm.getPageIndex(), newHouseImageForm.getPageSize());
        IPage<HouseImage> result = houseImageService.findAll(page, newHouseImageForm);
        map.addAttribute(Constants.PI, result);
        return String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除房屋图像信息
     *
     * @param imageId 主键
     * @return 页面
     */
    @ResponseBody
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除房屋图像信息")
    public String delete(@RequestParam("imageId") Long imageId, SessionStatus status) {
        HouseImage image = houseImageService.getById(imageId);
        houseImageService.removeById(image);
        status.setComplete();
        return Constants.OK;
    }

    /**
     * 打开房屋图像上传页面
     *
     * @param map  参数
     * @param path 路径
     * @param id   主键
     * @return 页面
     */
    @GetMapping("/upload")
    @SystemControllerLog(description = "打开房屋图像上传页面")
    public String openUploadPage(Model map, @RequestParam("path") String path, @RequestParam("id") Long id) {
        map.addAttribute(Constants.ID, id);
        map.addAttribute("path", path);
        map.addAttribute("list", houseImageService.findByHouseId(id));
        return UPLOADPAGE;
    }

    /**
     * 异步上传房屋图像记录
     *
     * @param file 文件
     * @return 页面
     */
    @PostMapping("/upload")
    @ResponseBody
    @SystemControllerLog(description = "异步上传房屋图像记录")
    public String ajaxPostUploadImage(@RequestParam("file") MultipartFile file) {
        String result = Constants.ERROR;
        try {
            if (file.getInputStream() != null) {
                files.add(file);
                result = Constants.OK;
            }
        } catch (IOException e) {
            throw new MyException(ExceptionEnum.INPUTEXCEPTION, e);
        }
        return result;
    }

    /**
     * 提交上传房屋图像记录
     *
     * @param map     参数
     * @param path    路径
     * @param id      主键
     * @param request 请求
     * @return 页面
     */
    @GetMapping("/uploadsubmit")
    @SystemControllerLog(description = "提交上传房屋图像记录")
    public String postUploadImage(Model map, @RequestParam("path") String path, @RequestParam("id") Long id,
                                  HttpServletRequest request) {
        if (files != null && !files.isEmpty()) {
            List<HouseImage> list = houseImageService.findByHouseId(id);
            int listSize = list == null ? 0 : list.size();

            if (listSize < 6 && listSize + files.size() <= 6) {
                houseImageService.insert(id, files, request);
            } else {
                files.clear();
                map.addAttribute("list", list);
                return HttpServletResponseUtil.processModelAndView(map, "最多可以上传6张图片", UPLOADPAGE);
            }
            files.clear();
        }
        return "redirect:/" + path + "/getAll";
    }

}
